package com.back.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import com.alibaba.fastjson.JSONObject;
import com.back.entity.Log;
import com.back.entity.User;
import com.back.entity.ValidGroup;
import com.back.service.impl.UserServiceImpl;
import com.back.service.inte.LogService;
import com.back.uitls.MyException;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.buf.HexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;

@Slf4j
@RestController
@RequestMapping("/api")
public class UserController {
    @Autowired
    UserServiceImpl userService;
    @Autowired
    LogService logService;

    @PostMapping("/login")
    SaResult login(@Validated(ValidGroup.User.Login.class) @RequestBody User user, HttpServletRequest request) {
        try {
            userService.login(user.getName(), user.getPwd());
            logService.add(Log.ok(request, "登陆成功"));
            return SaResult.ok("登陆成功");
        } catch (MyException e) {
            logService.add(Log.error(request, e.getMsg()));
            return SaResult.error(e.getMsg());
        } catch (Exception e) {
            logService.add(Log.error(request, "登录失败"));
            return SaResult.error("登录失败");
        }
    }

    @PostMapping("/register")
    SaResult register(@Validated(ValidGroup.User.Create.class) @RequestBody User user, HttpServletRequest request) {
        try {
            userService.register(user);
            logService.add(Log.ok(request, "注册成功"));
            return SaResult.ok("注册成功");
        } catch (MyException e) {
            logService.add(Log.error(request, e.getMsg()));
            return SaResult.error(e.getMsg());
        } catch (Exception e) {
            logService.add(Log.error(request, "注册失败"));
            return SaResult.error("注册失败");
        }
    }

    @GetMapping("/logout")
    SaResult logout(HttpServletRequest request) {
        try {
            StpUtil.checkLogin();
            StpUtil.logout();
            logService.add(Log.ok(request, "注销成功"));
            return SaResult.ok("注销成功");
        } catch (Exception e) {
            logService.add(Log.error(request, e.getMessage()));
            return SaResult.error(e.getMessage());
        }
    }


}
